package com.qk.dm.reptile.listener;

import com.alibaba.excel.annotation.ExcelProperty;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.groups.Default;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 *数据格式验证类
 */
public class EasyExcelValidateHelper {
  private static final List<String> ignoreFields = Arrays.asList("dsdLevelId", "dsdLevel");

  private EasyExcelValidateHelper() {}

  private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

  public static <T> String validateEntity(T obj) throws NoSuchFieldException {
    StringBuilder result = new StringBuilder();
    Set<ConstraintViolation<T>> set = validator.validate(obj, Default.class);
    if (set != null && !set.isEmpty()) {
      for (ConstraintViolation<T> cv : set) {
        if (!ignoreFields.contains(cv.getPropertyPath().toString())) {
          Field declaredField = obj.getClass().getDeclaredField(cv.getPropertyPath().toString());
          if (null != declaredField.getAnnotation(ExcelProperty.class)) {
            result.append(cv.getMessage()).append(";");
          }
        }
      }
    }
    return result.toString();
  }
}
